package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper bookMapper;

    /**
     * 添加收货地址
     *
     * @param addressBook
     * @return
     */
    @Override
    public int add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.get());
        addressBook.setCreateUser(BaseContext.get());
//        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateUser(BaseContext.get());
//        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setIsDefault(0);
        addressBook.setIsDeleted(0);
        //前端并没有提供省/市/表单，所以为空，不管了
        return bookMapper.insert(addressBook);
    }

    /**
     * 查询所有收货地址
     *
     * @return
     */
    @Override
    public List<AddressBook> findAll() {
        System.out.println("BaseContext.get() = " + BaseContext.get());
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, BaseContext.get());
        return bookMapper.selectList(lqw);
    }

    /**
     * 根据id删除收货地址
     *
     * @param id
     * @return
     */
    @Override
    public int deleteById(Long id) {
        return bookMapper.deleteById(id);
    }



    /**
     * 修改收货地址（修改信息）
     *
     * @param addressBook
     * @return
     */
    @Override
    public int update(AddressBook addressBook) {

        //判断用户执行的是何种操作
        LambdaUpdateWrapper<AddressBook> lqw = new LambdaUpdateWrapper<>();
        if (addressBook.getIsDefault() != null && addressBook.getIsDefault() == 1) {
            lqw.eq(AddressBook::getUserId, BaseContext.get()).set(AddressBook::getIsDefault, 0);
            bookMapper.update(null, lqw);
            return bookMapper.updateById(addressBook);
        }
        return bookMapper.updateById(addressBook);
    }


    //获得默认地址
    @Override
    public AddressBook getdefault(Long id) {
        LambdaQueryWrapper<AddressBook> qw= new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId,id);
        qw.eq(AddressBook::getIsDefault,1);
        return bookMapper.selectOne(qw);
    }
}
